<?php

namespace Home\Controller;
use Think\Controller;

//微信配置地址
class OfferController extends  BaseController {    
    /**
     * 前台控制器初始化 
     */
     function _initialize(){
       parent::_initialize();
    }
    
    //显示采购单需求
    public function index(){

     if(empty($this->opensession['userid']) || empty($this->opensession['openid'])){
         $this->redirect("Login/login?type='offer'");
         exit;
        }
        //获取到有效的采购单
        $wx_purchase_list =D('wx_purchase')->where('isactive =1')->select();
                //判断有效的采购单是否已经过期，过期就将该采购单的状态改成无效
        foreach ($wx_purchase_list as $key => $value) {
          $res = $this->time_if_overdue($value['lasttime'],$value['purchaseid']);
          if($res == true){
            unset($wx_purchase_list[$key]);
          }
       } 
       //print_r($wx_purchase_list);exit;
       $this->assign('wx_purchase_list',$wx_purchase_list);
       $this->display();

  }
 public function  offer_details(){
   $purchaseid = isset($_REQUEST['purchaseid']) ? trim($_REQUEST['purchaseid']) : '';
 if(IS_AJAX){
        //查询采购单标题我为开启状态的
        $where['purchaseid'] = $purchaseid;
        $where['number'] = array('gt',0);
        $msg=M("wx_purchaselist");
        if (!empty($_POST['pageNow'])) {
            $pageNow = $_POST['pageNow'];
        } else {
            $pageNow = 1;
        }

         $pageSize = 20;
          $count =$msg->where($where)->count(); // 查询满足要求的总记录数
          $numPage =ceil($count/$pageSize) ;
          if($pageNow > $numPage){
            echo "";
          }
          $pages = $pageSize * ($pageNow - 1)<=0 ? 0 :$pageSize * ($pageNow - 1) ;

          $ret=$msg->where($where)->limit( $pages,$pageSize )->order("createtime ASC")->select(); 
          if($ret == false){
            echo "";
          }
          foreach ($ret as $key => $value) {
              $value['goodsname'] = mb_substr($value['goodsname'], 0, 6, utf8);
              $ret[$key] = $value;
          }
         if($ret != false){
                 $this->assign('list',$ret);
                  $this->display('ajax');
          }else{
              echo "";

         }

    } else{
       

        $list = D('wx_purchase')->where('purchaseid = "'.$purchaseid.'"')->find();
        if($list == false){
            $this->error('采购单不存在');
        }
        //判断时间是否过期，过期就将状态改为无效（找到isactive=1）
         $where['purchaseid'] = $list['purchaseid'];

         $where['number'] = array('gt',0);

          $msg=M("wx_purchaselist");
           $pageSize = 20;
            $ret=$msg->where($where)->limit( 0,$pageSize )->order("createtime desc")->select(); 
          if($ret == false){
            $this->merror('采购单不存在');
          }
            foreach ($ret as $key => $value) {
              $value['goodsname'] = mb_substr($value['goodsname'], 0, 6, utf8);
              $ret[$key] = $value;
          }
        //$list['lasttime'] = date('Y年m月d日',strtotime($list['lasttime']));

         //获取供应商资料
         $user_id = $this->opensession['userid'];
         $supplier_list= D('wx_supplier')->where('user_id='.$user_id)->find();
         $this->assign('supplier_list', $supplier_list);
        $this->assign('content',$ret);
        $this->assign('list',$list);
        $this->assign('purchaseid',$purchaseid);
        $this->display('offer_details');
    }
 }

   //时间是否过期，并修改isactive=2
   public  function  time_if_overdue($lasttime,$purchaseid){
       $nowtime =strtotime(date('Y-m-d H:i:s')) ;
       $endtime = strtotime($lasttime);
       if($nowtime > $endtime){
         $where['isactive']=2;
         $res = D('wx_purchase')->where('purchaseid="'.$purchaseid.'"')->save($where);
         if($res){
            return true;
         }
       }
   }

    public function offertab(){
        //获取供应商资料

      
        $purchaseid = isset($_REQUEST['purchaseid']) ? trim($_REQUEST['purchaseid']) : '';
         $this->assign('purchaseid',$purchaseid);
         $user_id = $this->opensession['userid'];
         $supplier_list= D('wx_supplier')->where('user_id='.$user_id)->find();
         $this->assign('supplier_list', $supplier_list);
         $this->display();
    }


//提交供应商资料
public function set_supplier(){
 $ret=array('staute'=>'error','msg'=>"信息传递错误");
     $companyname = isset($_REQUEST['companyname']) ? trim($_REQUEST['companyname']) : '';
     $abncode = isset($_REQUEST['abncode']) ? trim($_REQUEST['abncode']) : '';
     $linkname = isset($_REQUEST['linkname']) ? trim($_REQUEST['linkname']) : '';
     $moblie = isset($_REQUEST['moblie']) ? trim($_REQUEST['moblie']) : '';
     $address = isset($_REQUEST['address']) ? trim($_REQUEST['address']) : '';
     if($companyname=="" ||$abncode ==""||$linkname ==""|| $moblie ==""||$address ==""){
        echo json_encode($ret);exit;
     }
     $user_id = $this->opensession['userid'];
     $supplierlist = D('wx_supplier')->where('user_id = '.$user_id)->find();
     if(!empty($supplierlist)){
          $save['companyname'] =$companyname;
          $save['abncode'] =$abncode;
          $save['linkname'] =$linkname;
          $save['moblie'] =$moblie;
          $save['address'] =$address;
        $res = D('wx_supplier')->where('user_id = '.$user_id)->save($save);
         if($res){
             $ret=array('staute'=>'success','msg'=>"数据完善成功");
             echo json_encode($ret);exit;
         }
     }
     //没有就添加新的供应商
     $sp_id = getGuid();
     $createtime = date('Y-m-d H:i:s');
     $sql3 = "INSERT INTO " . $this->dbprefix."wx_supplier  
     (sp_id, user_id,openid,companyname,abncode,address,linkname,moblie,isactive,createtime,operationuser) VALUES 
     ('".$sp_id."', ".$user_id.",'','".$companyname."','".$abncode."','".$address."','".$linkname."','".$moblie."',0,'".$createtime."',0)";
     $addres = M()->execute($sql3);
     if($addres){
        $ret=array('staute'=>'success','msg'=>"数据完善成功");
        echo json_encode($ret);exit;
     }
      $ret=array('staute'=>'error','msg'=>"数据保存失败");
       echo json_encode($ret);exit;

}

 public function  add_offer(){
$purchaseid = isset($_REQUEST['purchaseid']) ? trim($_REQUEST['purchaseid']) : '';
     $ret=array('staute'=>'error','msg'=>"保存失败");
      if($_POST['data'] == "" || $purchaseid==""){
        $ret=array('staute'=>'error','msg'=>"传输参数错误");
             $this->ajaxReturn ($ret);
            exit;
      }
    $json = json_decode($_POST['data'],true); 
        if(!is_array($json)){
            $ret=array('staute'=>'error','msg'=>"报价单信息错误");
            $this->ajaxReturn ($ret);
            exit;
        }

/*        //取得purchaseid
         $list = D('wx_purchase')->field('purchaseid')->where('isactive =1')->find();
         if(empty($list)){
            $ret=array('staute'=>'error','msg'=>"采购编号信息错误");
            $this->ajaxReturn ($ret);
         }*/
         //获取供应商
          $openid = $this->opensession['openid'];
          $supplierList = D('wx_supplier')->field('sp_id')->where("openid = '".$openid."' and isactive =1")->find();
          if(empty($supplierList )){
            $ret=array('staute'=>'error','msg'=>"供应商信息错误");
            $this->ajaxReturn ($ret);
          }
            $data['offerid'] = getGuid();
            $data['purchaseid'] = $purchaseid;
            $data['ishandle'] = 0;
            $data['isactive'] = 0;
            $data['check'] = 0;
            $data['createtime'] = date('Y-m-d H:i:s',strtotime(" +16 h"));
            $data['operationuser'] = 0;
            $data['sp_id'] = $supplierList['sp_id'];
           $res = D('wx_offer')->add($data);
           if($res == false){
             $ret=array('staute'=>'error','msg'=>"报价单提交错误");
             $this->ajaxReturn ($ret);
           }
           $offerid = $data['offerid'];
        //$purchaseid =  $data['purchaseid'];
            $iscomfirm = 0;
        $operationuser = 0;
        $createtime = date('Y-m-d H:i:s',strtotime(" +16 h"));
       $sqlval="";  
            foreach($json as $k=>$v){
            $code=getGuid();//创建guid值
          // $sqlval.=((empty($sqlval)?"":",").("('".$code."','".$offerid."','".$v['purchaseid']."','".$v['listid']."','".$v['number']."','".$v['offer_number']."','".$v['offer_price']."','".$v['sendtime']."','".$v['isbatch']."','"0"','".$operationuser."','".$createtime."')");
           $sqlval.=((empty($sqlval)?"":",")."('$code','$offerid','".$v['purchaseid']."','".$v['listid']."','".$v['offer_number']."','0','".$v['offer_price']."','".$v['sendtime']."','".$v['isbatch']."','$iscomfirm','$operationuser','$createtime')");             
             }
         $sqladd=" INSERT INTO  ".$this->dbprefix."wx_offerlist(`code`,`offerid`,`purchaseid`,`listid`,`offer_number`,`actual_number`,`offer_price`,`sendtime`,`isbatch`,`iscomfirm`,`operationuser`,`createtime`) values ".$sqlval;

         $db=M("wx_offerlist");
         $retadd=1;
         $db->startTrans(); //启动事务
         
         if($sqladd){
            $retadd=$db->execute($sqladd);
         } 

         if($retadd ){
            $db->commit();

                $user_mobile = D('wx_offer')->field('c.moblie,d.user_name,c.linkname')->alias('a')->join(" inner join  ".$this->dbprefix."wx_purchase as b on a.purchaseid = b.purchaseid ")
                 ->join(" inner join  ".$this->dbprefix."wx_supplier as c on a.sp_id = c.sp_id")->join(" inner join  ".$this->dbprefix."admin_user as d on b.operationuser = d.user_id")->where( "  a.offerid= '".$offerid."'")->find();
                $data['mobile'] = $user_mobile['moblie'];
                 //请求mobile/smsmessage_au.php
                 $url=C("WEBURL")."/mobile/smsmessage_au.php?act=purchase_message";
                //添加个参数区分需不需要构建session
                 $data['content'] ="51M管理员".$user_mobile['user_name']."你好，供应商".$user_mobile['linkname']."已经提交了供应单，请尽快到后台查看审核！";

                file_put_contents('log.txt', '\r\n'.date('Y-m-d H:i:s').$data['mobile'].$data['content'],FILE_APPEND);// 这个函数支持版本(PHP 5) 
                 
                 $result= $this->http_request($url,$data);
                 if($result=="" ||empty($result)){
                      $ret=array('staute'=>'success','msg'=>"短信发送失败");
                      $this->ajaxReturn($ret);
                   }

            $ret=array('staute'=>'success','msg'=>"保存数据成功");

         } else {
            $db->rollback();
            $ret=array('staute'=>'error','msg'=>"保存数据失败");
         } 
    $this->ajaxReturn($ret);



       


  }


  //用户显示当前报价单信息
  public  function user_offer(){
     $offerid = $_GET['offerid']?$_GET['offerid']:"";
    $offerid_list = D('wx_offer')->where("offerid ='".$offerid."' and isactive = 1 and ishandle =1")->field('check')->find();
       if(empty($offerid_list)){
           if(!($offerid_list['check'] ==3 || $offerid_list['check'] ==6)){
              $this->merror('该采购单已近审核完成或者不存在！');
           }
          
       }

      /*$offerid = "0E2C188C-CEC4-B8F3-CC5E-6D0F2F2421D4";*/
       if(!empty($offerid)){
           $list = D('wx_offerlist')->alias('a')->field('a.*,b.goodsname')->join(" left join ".$this->dbprefix."wx_purchaselist b on a.listid=b.listid")->where("offerid ='".$offerid."'")->select();
          if(!$list){
              $this->merror('采购商品不存在');
             }
   
           foreach ($list as $key => $value) {
              $value['goodsname'] = mb_substr($value['goodsname'], 0, 6, utf8);
              $number = $value['actual_number'];
              $sum_price +=  intval($value['offer_price'])*intval($number);
              $list[$key] = $value;

          }

            $purchaseid = D('wx_offer')->field('purchaseid')->where("offerid ='".$offerid."'")->find();
         
               $offername =D('wx_purchase')->field('purchaseame')->where("purchaseid='".$purchaseid['purchaseid']."'")->find();
         
                $this->assign('offername',$offername);
            $this->assign('sum_price',number_format($sum_price,2));
            $this->assign('list',$list);
            $this->assign('offerid',$offerid);
            $this->display();
          }else{
            $this->merror('没有报价单啦');
          }

  }



  public function  uploadoffer(){
     $offerid = $_GET['offerid'];
     if(empty($_GET['offerid'])){
      echo '没有该报价单!';
      exit;
     }
       $upload = new \Think\Upload();// 实例化上传类
      $upload->maxSize = 3145728;
      $upload->rootPath = './Images/invoice/';
      $upload->savePath = '';
      $upload->saveName = array('uniqid','');
      $upload->exts     = array('jpg', 'gif', 'png', 'jpeg');
      $upload->autoSub  = true;
      $upload->subName  = array('date','Ymd');
       // 上传文件 
      $info   =   $upload->upload($_FILES);
     
      if(!$info) {// 上传错误提示错误信息
          /*$this->merror($upload->getError());*/

          echo $upload->getError();
      }else{// 上传成功 获取上传文件信息
         $invoiceurl_arr = array();
          foreach($info as $k =>$file){
             $imgurl= $file['savepath'].$file['savename'];
             $invoiceurl_arr[$k] = 'invoice/'.$imgurl;
             } 
             $data['invoiceurl'] = implode(",",$invoiceurl_arr);
             $res = D('wx_offer')->where("offerid = '".$offerid."'")->save($data);
             if($res== false){
             $this->merror("上传失败");
              exit;
             }
         $db = M();
         $time = date('Y-m-d H:i:s',strtotime(" +16 h"));
        $res = $db->execute("update ".$this->dbprefix."wx_offer set `check` = 2,createtime='".$time."' where offerid='".$offerid."'");
        if($res){
          //发票上传成功后给  管理员发送消息
/*           $adminuser = D('wx_offer')->where("offerid = '".$offerid."'")->field('operationuser')->find();
           if(!$adminuser){
              $this->merror('获取管理员信息失败');
           }
           //获取管理员绑定的openid
           $adminopenid = D('wx_binduser')->field('openid')->where("user_id=".$adminuser['operationuser']." and bindtype ='admin'")->find();
           if(!$adminopenid){
              $this->merror('获取管理员微信失败');
           }
        $sd=array();
        $openid = $adminopenid['openid'];
        $url = C("WEBURL").'/adminindex.php/Offer/validate/offerid/0657E25B-7969-CEFA-9523-52740C5EF668';
        $sd['touser']='ok2DgvrrvVtMcnu8AZuBXZZm-nLY';
        $sd['msgtype']='text';
        $sd['text']['content']= urlencode("<a href='".$url."'>供应商提交了发票,点击查看</a>");

        $result = $this->SendMessage($sd);
             if( $result['errcode'] != 0 || $result['errmsg'] != "ok"){
                  $this->merror('信息发送失败!');
                  exit;
                 }else{
                   $this->redirect("Offer/index");
                 }*/
                 $user_mobile = D('wx_offer')->field('c.moblie,b.user_name,c.linkname')->alias('a')->join(" inner join  ".$this->dbprefix."admin_user as b on a.operationuser = b.user_id ")
                 ->join(" inner join  ".$this->dbprefix."wx_supplier as c on a.sp_id = c.sp_id")->where( "  a.offerid= '".$offerid."'")->find();
                $data['mobile'] = $user_mobile['moblie'];
                 //请求mobile/smsmessage_au.php
                 $url=C("WEBURL")."/mobile/smsmessage_au.php?act=purchase_message";
                //添加个参数区分需不需要构建session
                 $data['content'] ="51M管理员".$user_mobile['user_name']."你好，供应商".$user_mobile['linkname']."已经上传发票完成，请尽快到后台查看审核！";

                file_put_contents('log.txt', '\r\n'.date('Y-m-d H:i:s').$data['mobile'].$data['content'],FILE_APPEND);// 这个函数支持版本(PHP 5) 
                 
                 $result= $this->http_request($url,$data);
                 if($result=="" ||empty($result)){
                        //$this->success('消息发送失败!',$_SERVER['HTTP_ORIGIN']."/mobile/user.php?act=supply_list");
                         header('Location: /mobile/user.php?act=supply_list');
                   }
               header('Location: /mobile/user.php?act=supply_list');
                }else{
                 $this->merror("您确认失败啦");
             }
      


      }        
  }



//交易失败
  public function user_fail(){
     if(empty($_GET['offerid'])){
      $this->merror('验证异常');
     }
     $db = M();
     $offerid = $_GET['offerid'];
     $time = date('Y-m-d H:i:s',strtotime(" +16 h"));
     $res = $db->execute("update ".$this->dbprefix."wx_offer set `check` = 4,createtime='".$time."' where offerid='".$offerid."'");
     if($res){
          $user_mobile = D('wx_offer')->field('c.moblie,b.user_name,c.linkname')->alias('a')->join(" inner join  ".$this->dbprefix."admin_user as b on a.operationuser = b.user_id ")
          ->join(" inner join  ".$this->dbprefix."wx_supplier as c on a.sp_id = c.sp_id")->where( "  a.offerid= '".$offerid."'")->find();

         $data['mobile'] = $user_mobile['moblie'];
         //请求mobile/smsmessage_au.php
         $url=C("WEBURL")."/mobile/smsmessage_au.php?act=purchase_message";
        //添加个参数区分需不需要构建session
         $data['content'] ="51M管理员".$user_mobile['user_name']."你好，供应商".$user_mobile['linkname']."取消交易，交易失败！";
        file_put_contents('log.txt', '\r\n'.date('Y-m-d H:i:s').$data['mobile'].$data['content'],FILE_APPEND);// 这个函数支持版本(PHP 5) 
         $result= $this->http_request($url,$data);
         if($result=="" ||empty($result)){
           header('Location: /mobile/user.php?act=supply_list');exit;
         }
           header('Location: /mobile/user.php?act=supply_list');exit;
     }else{
      $this->merror("您确认失败啦");
     }

  }



        //HTTP请求（支持HTTP/HTTPS，支持GET/POST）
    function http_request($url, $data = null){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
}
?>